#!/usr/bin/env python

# uploadhere.py
#
# Written by Joseph Ku <chiehfang.ku@gmail.com>
# All rights reserved.

import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi

class HTTPHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write("""
                <HTML><BODY>
                
                <form method='POST' enctype='multipart/form-data' action='/'>
                    Select a file to upload: <input type="file" name="uploadfile" />
                    <br/>
                    <input type="submit" value="Upload" />
                </form>

                </BODY></HTML>
                """)
        return


    def do_POST(self):
        form = cgi.FieldStorage(fp=self.rfile,
                                headers=self.headers,
                                environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['content-type'],}
                               )
        field_item = form['uploadfile']
        print field_item.filename

        self.send_response(200)
        self.end_headers()

        open(field_item.filename, 'wb').write(field_item.file.read())
        self.wfile.write("<HTML><BODY>Done.</BODY></HTML>")

        return


def main(args):
    if len(args) == 2:
        port = int(args[1])
    else:
        print 'Default port: 8080'
        port = 8080

    try:
        server = HTTPServer(('', port), HTTPHandler)
        print 'HTTP Server has been started...'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'Shutting down the server'
        server.socket.close()

    return 0


if __name__ == '__main__':
    exit(main(sys.argv[0:]))

